<template>
	<view class="cart">
		<view class="top">共{{dataObj.list.length}}个商品</view>
		<view class="list">
			<view
				class="l-item"
				:class="pageObj.classObj[item.cat_type]"
				v-for="(item, idx) in dataObj.list"
				:key="item.id">
				<view
					class="content"
					:data-index="idx"
					@touchstart="drawStart"
					@touchmove="drawMove"
					@touchend="drawEnd"
					:style="'left:'+item.left+'px'">
					<view class="select" :class="item.selected ? 'selected' : ''" @click="onSelectTap(idx)"></view>
					<image class="cover" :src="item.products.image_path"></image>
					<view class="title ellipsis-2">{{item.products.name}}</view>
					<view class="info">
						单价：<span class="price">{{item.products.amount}}</span>
						<span class="type">{{item.products.app_cat_name}}</span>
					</view>
					<view class="opts" v-if="item.cat_type === 3">
						<image class="btn-del" @click="onOptsTap('reduce', idx)" src="../../static/images/cart/reduce.png"></image>
						<view class="number">{{item.nums}}</view>
						<image class="btn-add" @click="onOptsTap('add', idx)" src="../../static/images/cart/add.png"></image>
					</view>
				</view>
				<!-- 删除按钮 -->
				<view class="del-btn" @click="onDelTap(item)">删除</view>
			</view>
		</view>
		<view v-if="flag" class="footer">
			<view class="select-all" :class="pageObj.isALL ? 'selected' : ''" @click="onSelectAllTap">全选</view>
			<view class="sum">
				共{{sum}}个，合计：<span class="price">¥{{sumPrice}}</span>
			</view>
			<view class="btn" @click="onCheckTap('createOrder')">去结算</view>
		</view>
		<view v-if="!flag" class="footer">
			<view class="select-all" :class="pageObj.isALL ? 'selected' : ''" @click="onSelectAllTap">全选</view>
			<view class="sum">共{{sum}}个</view>
			<view class="btn black" @click="onCheckTap('del')">删除</view>
		</view>
	</view>
</template>

<script>
	import { requestErrorTip } from '@/common/tools.js';
	
	export default {
		data() {
			return {
				flag: true,
				pageObj: {
					classObj: ['', 'class', 'question', 'book', 'class'],
					touchObj: {
						startX: 0
					},
					delWidth: 0, //记录删除按钮宽度
					isALL: false
				},
				dataObj: {
					list: [],
					price: '0'
				}
			}
		},
		computed: {
			// 选中商品数量
			sum: function() {
				let sum = 0;
				let hasNoSelect = false; // 判断是否存在一个数据没有选中
				for(let i in this.dataObj['list']){
					const item = this.dataObj['list'][i];
					if (item['selected']) {
						sum++;
					} else {
						hasNoSelect = true;
					}
				}
				if (hasNoSelect || this.dataObj['list'].length === 0) {
					// 至少一个未有选中，则设置全部为选中
					this.pageObj['isALL'] = false;
				} else {
					// 全部都选中的，则设置全部为不选中
					this.pageObj['isALL'] = true;
				}
				return sum;
			},
			// 合计价格
			sumPrice: function() {
				let money = 0;
				for(let i in this.dataObj['list']){
					const item = this.dataObj['list'][i];
					const product = this.dataObj['list'][i]['products'];
					const number = this.dataObj['list'][i]['nums'];
					if (item['selected']) {
						money += parseFloat(product['amount']) * number;
					}
				}
				return money.toFixed(2);
			}
		},
		onShow() {
			const that = this;
			that.dataObj['list'] = [];
			// 获取用户信息
			uni.getStorage({
				key: 'token',
				success: function (res) {
					console.log(res, 'res');
					// 已存储userInfo(登陆)
					that.getData();
				},
				fail: function (err) {
					// 未存储userInfo(登陆)，页面跳至“登陆页”
					// uni.reLaunch({
					// 	url: '/pages/account/login'
					// });
				}
			});
		},
		onNavigationBarButtonTap(e) {
			var currentWebview = this.$mp.page.$getAppWebview();
			var tn = currentWebview.getStyle().titleNView;
			if (this.flag) {
				tn.buttons[0].text = '完成';
			} else {
				tn.buttons[0].text = '管理';
			}
			this.flag = !this.flag;
			currentWebview.setStyle({
				titleNView: tn
			});
			this.dataObj['list'] = this.dataObj['list'].filter((item) => {
				item.selected = false;
				return item;
			})
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.getData();
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: {
			init() {
				// select中的参数就如css选择器一样选择元素
				const query = uni.createSelectorQuery().in(this);
				query.select('.del-btn').boundingClientRect(data => {
					console.log(data, 'data');
					this.pageObj['delWidth'] = data.width;
				}).exec();
			},
			// 选择单个
			onSelectTap(index) {
				this.dataObj['list'][index]['selected'] = !this.dataObj['list'][index]['selected'];
			},
			// 滑动的开始事件
			drawStart(e) {
				const touch = e.touches[0];
				this.pageObj['touchObj']['startX'] = touch.clientX;
			},
			// 滑动的移动事件
			drawMove(e) {
				const delWidth = this.pageObj['delWidth'];
				const touch = e.touches[0];
				const index = e.currentTarget.dataset.index;
				const disX = touch.clientX - this.pageObj['touchObj']['startX'];
				if (disX < 0) {
					if (disX < -(delWidth * 0.4)) {
						this.dataObj['list'][index]['left'] = -delWidth;
						return false;
					}
					this.dataObj['list'][index]['left'] = disX;
				} else {
					if (this.dataObj['list'][index]['left'] + disX > 0) {
						this.dataObj['list'][index]['left'] = 0;
						return false;
					}
					this.dataObj['list'][index]['left'] += disX;
				}
			},
			// 滑动的结束事件
			drawEnd(e) {
				const delWidth = this.pageObj['delWidth'];
				const index = e.currentTarget.dataset.index;
				const left = this.dataObj['list'][index]['left'];
				if (-left < delWidth * 0.4) {
					this.dataObj['list'][index]['left'] = 0;
				}
			},
			// 删除商品
			onDelTap(item) {
				this.postDelData(item.id, () => {
					const index = this.dataObj['list'].indexOf(item);
					if (index > -1) {
						this.dataObj['list'].splice(index, 1);
					}
				});
			},
			// 增减操作
			onOptsTap(type, index) {
				if (type === 'reduce') {
					// 减少
					if (this.dataObj['list'][index]['nums'] <= 1) {
						return false;
					}
					this.dataObj['list'][index]['nums']--;
				} else {
					// 增加
					this.dataObj['list'][index]['nums']++;
				}
				this.postSetNUm(this.dataObj['list'][index]);
			},
			// 设置商品数量
			postSetNUm(item) {
				this.$Requset({
					url: this.$Api['cart']['setnums'],
					data: {
						id: item['id'],
						nums: item['nums'],
						type: 0
					},
					loading: false,
					success: (res) => {
						const { msg } = res;
						requestErrorTip('toast', msg);
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 选择全部
			onSelectAllTap() {
				let hasNoSelect = false; // 判断是否存在一个数据没有选中
				for(let i in this.dataObj['list']){
					if (!this.dataObj['list'][i]['selected']) {
						hasNoSelect = true;
					}
				}
				if (hasNoSelect) {
					// 至少一个未有选中，则设置全部为选中
					this.pageObj['isALL'] = true;
					for(let i in this.dataObj['list']){
						this.dataObj['list'][i]['selected'] = true;
					}
				} else {
					// 全部都选中的，则设置全部为不选中
					this.pageObj['isALL'] = false;
					for(let i in this.dataObj['list']){
						this.dataObj['list'][i]['selected'] = false;
					}
				}
			},
			// 购物车操作检查
			onCheckTap(type) {
				const that = this;
				// 非微信
				// #ifndef MP-WEIXIN
				uni.getStorage({
					key: 'token',
					success: function (res) {
						let ids = '';
						for(let i in that.dataObj['list']) {
							const item = that.dataObj['list'][i];
							if (item['selected']) {
								if (ids) {
									ids += ',' + item['id'];
								} else {
									ids = item['id'];
								}
							}
						}
						if (that.dataObj['list'].length === 0) return false
						if (that.sum <= 0) {
							// 显示模态框
							uni.showModal({
								title: '温馨提示',
								showCancel: false,
								content: '您还未选择商品哦！',
								confirmColor: '#FE6B00'
							});
							return false;
						}
						if (type === 'createOrder') {
							// 结算
							that.onCreateOrderTap(ids)
						} else if (type === 'del') {
							// 删除
							that.postDelData(ids, () => {
								that.dataObj['list'] = [];
								that.getData();
							})
						}
					},
					fail: function (err) {
						// 未存储userInfo(登陆)，页面跳至“登陆页”
						uni.reLaunch({
							url: '/pages/account/login'
						});
					}
				});
				// #endif
				
				// 微信
				// #ifdef MP-WEIXIN
				requestErrorTip('toast', '由于相关规范，IOS功能暂不可用');
				// #endif
			},
			// 结算
			onCreateOrderTap(ids) {
				uni.navigateTo({
					url: '/pages/order/create-order?ids=' + ids
				});
			},
			// 获取购物车全部商品
			getData() {
				this.$Requset({
					url: this.$Api['cart']['list'],
					data: {},
					success: (res) => {
						const { data, status, msg } = res;
						if (!status) {
							requestErrorTip('toast', msg);
							return;
						}
						if (data['list'].length > 0) {
							const list = data['list'].filter(item => {
								item['selected'] = false;
								item['left'] = 0;
								return item;
							});
							this.dataObj['list'] = list || [];
							setTimeout(() => {
								this.init();
							}, 200);
						} else {
							requestErrorTip('toast', '没有更多数据');
						}
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 提交删除购物车接口
			postDelData(id, callBack) {
				this.$Requset({
					url: this.$Api['cart']['del'],
					data: {
						ids: id
					},
					success: (res) => {
						const { data, status } = res;
						if (!status) {
							return;
						}
						callBack && callBack();
					},
					fail: (err) => {
						requestErrorTip('toast', err);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page{
		background-color: #f5f5f5;
	}
	.cart{
		width: 100%;
		position: relative;
		padding-bottom: 90rpx;
		.top{
			line-height: 68rpx;
			font-size: 22rpx;
			color: #7F7F7F;
			padding-left: 36rpx;
		}
		.list{
			.l-item{
				position: relative;
				height: 222rpx;
				border-radius: 22rpx;
				margin-bottom: 20rpx;
				background-color: $color-common;
				.del-btn{
					position: absolute;
					top: 0;
					right: 0;
					width: 100rpx;
					height: 100%;
					line-height: 222rpx;
					font-size: 28rpx;
					color: #FFFFFF;
					text-align: center;
				}
				.content{
					box-sizing: border-box;
					position: absolute;
					z-index: 1;
					width: 100%;
					top: 0;
					left: 0;
					width: 100%;
					padding: 32rpx 36rpx 32rpx 370rpx;
					border-radius: 22rpx;
					background-color: #FFFFFF;
					.select{
						position: absolute;
						top: 32rpx;
						left: 36rpx;
						width: 40rpx;
						height: 40rpx;
						background-repeat: no-repeat;
						background-position: center center;
						background-size: 100%;
						background-image: url(../../static/images/cart/select.png);
					}
					.selected{
						background-image: url(../../static/images/cart/selected.png);
					}
					.cover{
						position: absolute;
						top: 32rpx;
						left: 98rpx;
						background-color: #F7F7F7;
						border-radius: 14rpx;
					}
					.title{
						height: 80rpx;
						line-height: 40rpx;
						font-size: 26rpx;
						color: #1A1A1A;
					}
					.info{
						height: 46rpx;
						line-height: 46rpx;
						font-size: 22rpx;
						color: #7F7F7F;
						.price{
							font-size: 30rpx;
							font-weight: bold;
							color: $color-common;
						}
						.type{
							float: right;
						}
					}
					.opts{
						float: right;
						display: flex;
						height: 46rpx;
						line-height: 46rpx;
						width: 150rpx;
						font-size: 28rpx;
						border-radius: 8rpx;
						border: 1rpx solid #ddd;
						text-align: center;
						.btn-del, .btn-add{
							flex: 1;
							height: 46rpx;
							width: 46rpx;
						}
						.number{
							flex: 1;
							color: $color-common;
							border-left: 1rpx solid #ddd;
							border-right: 1rpx solid #ddd;
						}
					}
				}
			}
			.question,
			.class{
				.content{
					height: 222rpx;
					padding: 32rpx 36rpx 32rpx 370rpx;
					.cover{
						width: 254rpx;
						height: 158rpx;
					}
					.title{
						height: 80rpx;
						margin-bottom: 32rpx;
					}
				}
			}
			.book{
				height: 246rpx;
				.del-btn{
					line-height: 246rpx;
				}
				.content{
					height: 246rpx;
					padding: 32rpx 36rpx 32rpx 260rpx;
					.cover{
						width: 144rpx;
						height: 180rpx;
					}
					.title{
						// height: 120rpx;
						margin-bottom: 12rpx;
					}
					.info{
						margin-bottom: 4rpx;
					}
				}
			}
		}
		.footer{
			box-sizing: border-box;
			position: fixed;
			z-index: 99;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 90rpx;
			padding: 10rpx 200rpx 10rpx 36rpx;
			background-color: #FFFFFF;
			// #ifdef H5
			bottom: 100rpx;
			left: 50%;
			margin-left: -200px;
			width: 400px;
			// #endif
			.select-all{
				float: left;
				position: relative;
				line-height: 70rpx;
				width: 66rpx;
				font-size: 26rpx;
				color: #1A1A1A;
				padding-left: 48rpx;
				margin-right: 14rpx;
				&::before{
					content: '';
					position: absolute;
					top: 50%;
					margin-top: -20rpx;
					left: 0;
					width: 40rpx;
					height: 40rpx;
					background-repeat: no-repeat;
					background-position: center center;
					background-size: 100%;
					background-image: url(../../static/images/cart/select.png);
				}
				&::after{
					content: '';
					position: absolute;
					top: 50%;
					margin-top: -18rpx;
					right: 0;
					width: 1rpx;
					height: 36rpx;
					background-color: #E4EAED;
				}
			}
			.selected{
				&::before{
					background-image: url(../../static/images/cart/selected.png);
				}
			}
			.sum{
				line-height: 70rpx;
				font-size: 26rpx;
				color: #1A1A1A;
				.price{
					font-size: 40rpx;
					font-weight: bold;
					color: $color-common;
					vertical-align: bottom;
				}
			}
			.btn{
				position: absolute;
				top: 10rpx;
				right: 36rpx;
				width: 200rpx;
				height: 70rpx;
				line-height: 70rpx;
				font-size: 26rpx;
				color: #FFFFFF;
				text-align: center;
				background-color: $color-common;
				border-radius: 35rpx;
			}
			.black {
				background-color: #333;
			}
		}
	}
</style>
